import axios from 'axios';

//测试环境基址
const BASE_URL = 'http://127.0.0.1:8088/demo';
const unAuthMap = new Map([['/user/login', 'post']]);
import { Local } from '@/utils/storage';

const AxiosRequest = axios.create({
  baseURL: BASE_URL,
  timeout: 60000, // 超时时间
});

// 设置请求拦截器
AxiosRequest.interceptors.request.use(
  (config) => {
    const isUnAuthRoute = unAuthMap.has(config.url) && unAuthMap.get(config.url) === config.method.toLowerCase();
    if (!isUnAuthRoute) {
      const token = Local.get('token');
      if (!token) {
        return Promise.reject({
          error: 'apiError-notoken',
          message: 'token为空',
        });
      }
      config.headers['Authorization'] = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 设置响应拦截器
AxiosRequest.interceptors.response.use(
  (res) => {
    if (res.config.url === '/user/login') {
      let token = res.data.data.token;
      if (token) {
          Local.set('token', token);
      }
    }
    return res;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export { AxiosRequest, BASE_URL };
